package com.example.zhinongbao.utils;

import com.example.zhinongbao.model.CartItem;
import com.example.zhinongbao.model.Product;
import java.util.ArrayList;
import java.util.List;

public class CartManager {
    private static CartManager instance;
    private List<CartItem> cartItems = new ArrayList<>();

    private CartManager() {}

    public static synchronized CartManager getInstance() {
        if (instance == null) {
            instance = new CartManager();
        }
        return instance;
    }

    // 添加商品到购物车
    public void addToCart(Product product, int quantity) {
        for (CartItem item : cartItems) {
            if (item.getProduct().getId() == product.getId()) {
                item.setQuantity(item.getQuantity() + quantity);
                return;
            }
        }
        cartItems.add(new CartItem(product, quantity));
    }

    // 获取购物车所有商品
    public List<CartItem> getCartItems() {
        return new ArrayList<>(cartItems);
    }

    // 获取购物车商品总数
    public int getTotalCount() {
        int count = 0;
        for (CartItem item : cartItems) {
            count += item.getQuantity();
        }
        return count;
    }

    // 获取购物车总金额
    public double getTotalPrice() {
        double total = 0;
        for (CartItem item : cartItems) {
            total += item.getProduct().getPrice() * item.getQuantity();
        }
        return total;
    }

    // 清空购物车
    public void clearCart() {
        cartItems.clear();
    }
}